import Vue from "vue";
import axios from "axios";

axios.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    response => {
        const { data, status } = response;
        if (status >= 500 && status <= 505) {
            return null;
        }
        if (status === 200 || status === 304) {
            return data;
        }
    },
    error => Promise.resolve(error.response)
);
let msgSoft = null
function checkCode(res) {
    if (!res) return null
    const { code } = res;
    if (code === 200) {
        return res;
    } else {
        if (msgSoft) {
            return res;
        } else {
            return null;
        }
    }
}

export default (url, val, msg = null) => {
    msgSoft = msg
    let jsons = {};
    let mid = Vue.prototype.$token.getCookie("member_id")
    if (mid) jsons.member_id = mid
    let dataVal = { ...jsons, ...val };
    return axios({
        method: "post",
        url: '/api/' + url,
        data: dataVal,
        timeout: 10000
    }).then(checkCode);
};